package cn.com.infcn.Task;

import cn.com.infcn.util.ConfigUtils;
import cn.com.infcn.util.FileUtils;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by cc on 2016/12/28.
 * @author jijs
 */
public class TimerTask {

    public static void main(String[] args) {
        execute();
    }

    public static void execute() {

        Runnable runnable = new Runnable() {
            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
                final String dateStr = sdf.format(new Date());

                String dir = ConfigUtils.getTempFileDirector();
                File file = new File(dir);
                File[] files = file.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return !dateStr.equals(name);
                    }
                });

                if (files != null) {
                    for (File f : files) {
                        FileUtils.deleteFile(f);
                    }
                }
            }
        };
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();

        long internalTime = 24*60*60*1000;

        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable, execTime(), internalTime, TimeUnit.MILLISECONDS);

        runnable.run();
    }



    private static long execTime(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 1);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        cal.clear();
        cal.set(year, month, day);

        long currentTime = System.currentTimeMillis();
        long execTime = cal.getTimeInMillis();

        return execTime-currentTime;
    }
}
